module.exports = function ({Categories}) {
    /**
     * 查询Tree V2
     */
    Categories.treeV2 = function () {
        return Categories.findAll({
            order: [['parent_id', 'asc'], ['order_by', 'asc'], ['id', 'asc']],
            attributes: ['id', ['name', 'text'], 'parent_id'],
            raw: true
        }).then(function (rows) {
            let recursion = function (category, categories) {
                let children = category.children = [];
                for (let i in categories) {
                    let sub_category = categories[i];
                    if (sub_category.parent_id == category.id) {
                        children.push(sub_category);
                        recursion(sub_category, categories);
                    }
                }
                if (!children.length) {
                    delete category.children;
                }
            }
            let tree = [];
            for (let i in rows) {
                let category = rows[i];
                if (category.parent_id === null) {
                    tree.push(category);
                    recursion(category, rows);
                }
            }
            return tree;
        });
    }
}